package com.iceland.common.message;

import com.iceland.common.kryo.KryoUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CmdMessagEncoder extends MessageToByteEncoder {
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {

        CmdMessage m=(CmdMessage)msg;
        ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer();
        buffer.writeInt(m.getType());
        Header header = m.getHeader();
        if(header==null || header.size()==0){
            buffer.writeInt(0);
        }
        else {
            byte[] bytes = KryoUtil.writeToByteArray(header);
            buffer.writeInt(bytes.length);
            buffer.writeBytes(bytes);
        }

        if(m.data!=null){
            if(m.data instanceof ByteBuf){
                buffer.writeByte(DataType.BYTEBUF.getType());
                ByteBuf dataB=m.getData();
                buffer.writeBytes(dataB);
                dataB.release();
            }
            else {
                buffer.writeByte(DataType.SERIALIZE_OBJECT.getType());
                byte[] bytes = KryoUtil.writeToByteArray(m.data);
                buffer.writeBytes(bytes);
            }
        }
        out.writeInt(buffer.readableBytes());
        out.writeBytes(buffer);
        buffer.release();
    }
}